﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Acme.BookStore2.EntityFrameworkCore
{
    public class VehicleRepository : EfCoreRepository<BookStore2DbContext, Vehicle, Guid>, IVehicleRepository
    {
        public VehicleRepository(IDbContextProvider<BookStore2DbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public virtual async Task<List<Vehicle>> GetPagedListAsync(
            string sorting = null,
            int maxResultCount = int.MaxValue,
            int skipCount = 0,
            string number = null,
            string licensePlateNumber = null,
            bool? isMaintaining = null,
            bool includeDetails = false,
            CancellationToken cancellationToken = default)
        {
            return await DbSet
                .WhereIf(!number.IsNullOrWhiteSpace(), v => v.Number.Contains(number))
                .WhereIf(!licensePlateNumber.IsNullOrWhiteSpace(), v => v.LicensePlateNumber.Contains(licensePlateNumber))
                .WhereIf(isMaintaining.HasValue, v => v.IsMaintaining == isMaintaining)
                .OrderBy(sorting ?? nameof(Vehicle.CreationTime) + " desc")
                .PageBy(skipCount, maxResultCount)
                .ToListAsync(GetCancellationToken(cancellationToken));
        }
        
        public virtual async Task<long> GetCountAsync(
            string number = null,
            string licensePlateNumber = null,
            bool? isMaintaining = null,
            CancellationToken cancellationToken = default)
        {
            return await this
                .WhereIf(!number.IsNullOrWhiteSpace(), v => v.Number.Contains(number))
                .WhereIf(!licensePlateNumber.IsNullOrWhiteSpace(), v => v.LicensePlateNumber.Contains(licensePlateNumber))
                .WhereIf(isMaintaining.HasValue, v => v.IsMaintaining == isMaintaining)
                .LongCountAsync(GetCancellationToken(cancellationToken));
        }

        public virtual async Task<bool> AnyAsync(
            Expression<Func<Vehicle, bool>> predicate,
            Guid? ignoredId = null,
            CancellationToken cancellationToken = default)
        {
            return await DbSet
                .WhereIf(ignoredId != null, ct => ct.Id != ignoredId)
                .CountAsync(predicate, GetCancellationToken(cancellationToken)) > 0;
        }
        
        
    }
}